import Arrow from '../sprite/arrow.js'

export default class FollowMouse {
  constructor() {
    this.canvas = wx.createCanvas()
    this.context = this.canvas.getContext('2d')
    this.sprites = []
    this.loop = this.drawFrame.bind(this)
    this.touchHandler = this.touchEventHandler.bind(this)
    wx.onTouchMove(this.touchHandler)

    this.arrow = new Arrow()
    this.addChild(this.arrow)
    this.arrow.x = this.canvas.width / 2
    this.arrow.y = this.canvas.height / 2
    this.speed = 1
  }

  touchEventHandler(e) {
    let dx = e.touches[0].clientX - this.arrow.x,
        dy = e.touches[0].clientY - this.arrow.y,
        angle = Math.atan2(dy, dx),
        vx = Math.cos(angle) * this.speed,
        vy = Math.sin(angle) * this.speed
    this.arrow.rotation = angle
    this.arrow.x += vx
    this.arrow.y += vy
  }

  addChild(sprite) {
    if (sprite) {
      this.sprites.push(sprite)
    }
  }

  drawFrame() {
    requestAnimationFrame(this.loop)
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
    for (let sprite of this.sprites) {
      sprite.draw(this.context)
    }
  }
}